package me.zhengjie.modules.quartz.task;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.domain.AreaConf;
import me.zhengjie.config.DistrictEnum;
import me.zhengjie.config.SpecialAddressEnum;
import me.zhengjie.modules.gis.domain.*;
import me.zhengjie.modules.gis.domainSmart.MesAreaData;
import me.zhengjie.modules.gis.domainSmart.SmartWeighbridgeData;
import me.zhengjie.modules.gis.domainTrans.TransAreaData;
import me.zhengjie.modules.gis.repository.*;
import me.zhengjie.modules.gis.repositorySmart.SmartWeighbridgeDataRepository;
import me.zhengjie.modules.gis.service.AreaConfService;
import me.zhengjie.utils.map.GaodeMapUtils;
import me.zhengjie.utils.map.LonlatConver;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.persistence.criteria.Predicate;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 定时任务类
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TestTask {

    private final FeedHistoryRepository feedHistoryRepository;
    private final TimeLineRepository timeLineRepository;
    private final AreaConfRepository areaConfRepository;

    private final TransportationInHistoryRepository transportationInHistoryRepository;
    private final TransportationOutHistoryRepository transportationOutHistoryRepository;

    private final TransportationRepository transportationRepository;
    private final WeighbridgeInRepository weighbridgeInRepository;
    private final WeighbridgeOutRepository weighbridgeOutRepository;
    private final SmartWeighbridgeDataRepository smartWeighbridgeDataRepository;
    private final AreaConfService areaConfService;

    //苏再生原点(高德坐标系)
    private static final String location_suzaisheng = "120.455956,31.397547";
    //武进事业部原点(高德坐标系)
    private static final String location_shiyebu= "119.886007,31.680414";
    //无锡绿致和原点(高德坐标系)
    private static final String location_lvzhihe = "120.303546,31.566219";

    public void run(){
        log.info("run 执行成功");
    }

    public void run1(String str){
        log.info("run1 执行成功，参数为： {}" + str);
    }

    public void run2(){
        log.info("run2 执行成功");
    }


    /**
     * 同步特殊地点的路径
     */
    public void setLineData() {
        List<AreaConf> existAreas = areaConfRepository.findAll();
        List<AreaConf> areaConfToUpdate = existAreas.stream()
                .filter(areaConf ->
                        areaConf.getType() != null && (areaConf.getType() == 2 || areaConf.getType() == 3 || (areaConf.getType() >=5 && areaConf.getType() <=8))
                                && StringUtils.isBlank(areaConf.getLine()) && StringUtils.isNotBlank(areaConf.getPositionGcj02()))
                .collect(Collectors.toList());
        log.info("找到未规划路径的数据 " + areaConfToUpdate.size() + " 条");
        if (areaConfToUpdate.isEmpty()) {
            return;
        }
        for (AreaConf areaConf: areaConfToUpdate) {
            String[] splits = areaConf.getPositionGcj02().split(",");
            double[] centers = LonlatConver.gcj02_To_Wgs84(Double.parseDouble(splits[0]), Double.parseDouble(splits[1]));
            if (StringUtils.isBlank(areaConf.getPosition())) {
                areaConf.setPosition(centers[0] + "," + centers[1]);
            }

            //做路径规划
            String facLocation = "";
            int type = areaConf.getType();
            boolean isYingYong = false;
            switch (type) {
                case 2:
                    isYingYong = true;
                case 3:
                    facLocation = location_suzaisheng;
                    break;
                case 5:
                    isYingYong = true;
                case 6:
                    facLocation = location_lvzhihe;
                    break;
                case 7:
                    isYingYong = true;
                case 8:
                    facLocation = location_shiyebu;
                    break;
            }

            String[] origins = isYingYong ? facLocation.split(",") : splits;
            String[] dests = isYingYong ? splits : facLocation.split(",");
            List<BigDecimal[]> routes = GaodeMapUtils.routePlan(origins[0], origins[1], dests[0], dests[1]);
            if (!routes.isEmpty()) {
                routes.forEach(ArrayUtil::reverse);
                areaConf.setLine(JSON.toJSONString(routes));
            }
        }
        areaConfService.updateBatch(areaConfToUpdate);
        log.info("执行路径规划完成，同步了" + areaConfToUpdate.size() + "条数据");
    }

    /**
     * 导入MES系统地磅的所有地点，预存地点和路径数据
     */
    public void retrieveMesArea() {
        List<AreaConf> existAreas = areaConfRepository.findAll();
        HashMap<String, AreaConf> existArea = new HashMap<>();
        for (AreaConf areaConf: existAreas) {
            Integer type = areaConf.getType();
            if (type == null || type <= 1 || type >= 4) {
                continue;
            }
            existArea.put(type + "," + areaConf.getGisAreaName(), areaConf);
        }
        List<MesAreaData> sourceUnitList = areaConfService.getMesAreaDataList(0);
        List<MesAreaData> handleUnitList = areaConfService.getMesAreaDataList(1);
        sourceUnitList.addAll(handleUnitList);
        List<AreaConf> areasToSave = new ArrayList<>();
        List<AreaConf> areasToUpdate = new ArrayList<>();
        for (MesAreaData unitData: sourceUnitList) {
            //type=2 出料; type=3 进料
            int type = StringUtils.equals(unitData.getTransportUnitInnerCode(), "0") ? 2 : 3;
            String address = type == 2 ? unitData.getHandleUnit() : unitData.getSourceUnit();
            String key = type + "," + address;
            if (StringUtils.isBlank(address) || address.length() < 2 || StringUtils.contains(address, "退货")
                    || StringUtils.contains(address, "退票") || StringUtils.contains(address, "个人")
                    || StringUtils.contains(address, "退料") || StringUtils.contains(address, "不装")) {
                continue;
            }
            AreaConf areaConf = existArea.get(key);
            //position=null,代表无法找到对应地点；line!=null,代表已经做过路径规划
            if (areaConf != null && (areaConf.getPosition() == null || StringUtils.isNotBlank(areaConf.getLine()))) {
                continue;
            }
            boolean isCreate = false;
            if (areaConf == null) {
                areaConf = new AreaConf();
                areaConf.setGisAreaName(address);
                areaConf.setType(type);
                areaConf.setPositionGcj02(null);
                areaConf.setPosition(null);
                areaConf.setCity("苏州市");
                areaConf.setDistrict(unitData.getArea());
                isCreate = true;
            }

            //填入地点坐标
            if (StringUtils.isBlank(areaConf.getPosition())) {
                //先判断是否为特殊的地址
                SpecialAddressEnum addressEnum = SpecialAddressEnum.getSpecialAddress(address);
                if (addressEnum != null) {
                    areaConf.setPositionGcj02(addressEnum.getLng().toPlainString()+ "," + addressEnum.getLat().toPlainString());
                } else {
                    //使用高德API查找有无此地点数据，若没有，则定位到所在辖区的中心
                    AreaConf unit = GaodeMapUtils.searchLocation("苏州市", address);
                    if (unit == null) {
                        if (StringUtils.isNotBlank(unitData.getArea())) {
                            DistrictEnum districtEnum = DistrictEnum.getByDistrictName("苏州市", unitData.getArea());
                            if (districtEnum != null) {
                                if (StringUtils.isBlank(areaConf.getDistrict()) || DistrictEnum.getByDistrictName("苏州市", areaConf.getDistrict()) == null) {
                                    areaConf.setDistrict(districtEnum.getDistrict());
                                }
                                areaConf.setPositionGcj02(districtEnum.getLng().toPlainString() + "," + districtEnum.getLat().toPlainString());
                            }
                        }
                    } else {
                        //如果查到了此地点
                        if (StringUtils.isBlank(areaConf.getDistrict()) || DistrictEnum.getByDistrictName("苏州市", areaConf.getDistrict()) == null) {
                            areaConf.setDistrict(unit.getDistrict());
                        }
                        areaConf.setPositionGcj02(unit.getPositionGcj02());
                    }
                }
            }

            if (StringUtils.isNotBlank(areaConf.getPositionGcj02())) {
                String[] splits = areaConf.getPositionGcj02().split(",");
                double[] centers = LonlatConver.gcj02_To_Wgs84(Double.parseDouble(splits[0]), Double.parseDouble(splits[1]));
                areaConf.setPosition(centers[0] + "," + centers[1]);
                //做路径规划
                String[] origins = type == 2 ? location_suzaisheng.split(",") : splits;
                String[] dests = type == 2 ? splits : location_suzaisheng.split(",");
                List<BigDecimal[]> routes = GaodeMapUtils.routePlan(origins[0], origins[1], dests[0], dests[1]);
                if (!routes.isEmpty()) {
                    routes.forEach(ArrayUtil::reverse);
                    areaConf.setLine(JSON.toJSONString(routes));
                }
            }

            if (isCreate) {
                areasToSave.add(areaConf);
            } else {
                areasToUpdate.add(areaConf);
            }

        }
        if (!areasToSave.isEmpty()) {
            areaConfService.insertBatch(areasToSave);
        }
        if (!areasToUpdate.isEmpty()) {
            areaConfService.updateBatch(areasToUpdate);
        }

    }

    /**
     * 导入MES系统地磅的所有地点，预存地点和路径数据
     */
    public void retrieveTransArea() {
        List<AreaConf> existAreas = areaConfRepository.findAll();
        HashMap<String, AreaConf> existArea = new HashMap<>();
        for (AreaConf areaConf: existAreas) {
            Integer type = areaConf.getType();
            if (type == null || type < 7 || type > 8) {
                continue;
            }
            existArea.put(type + "," + areaConf.getGisAreaName(), areaConf);
        }
        List<TransAreaData> sourceUnitList = areaConfService.getTransAreaDataList(0);
        List<TransAreaData> handleUnitList = areaConfService.getTransAreaDataList(1);
        sourceUnitList.addAll(handleUnitList);
        List<AreaConf> areasToSave = new ArrayList<>();
        List<AreaConf> areasToUpdate = new ArrayList<>();
        for (TransAreaData unitData: sourceUnitList) {
            //type=7 出料; type=8 进料
            int type = StringUtils.equals(unitData.getTransportUnitInnerCode(), "0") ? 7 : 8;
            String address = type == 7 ? (StringUtils.isBlank(unitData.getProjectName()) ? unitData.getHandleUnit() : unitData.getProjectName()) : unitData.getSourceUnit();
            if (StringUtils.isBlank(address) || address.length() < 4 || StringUtils.contains(address, "退货")
                    || StringUtils.contains(address, "退票") || StringUtils.contains(address, "个人")
                    || StringUtils.contains(address, "退料") || StringUtils.contains(address, "不装")
                    || StringUtils.contains(address, "车间") || StringUtils.contains(address, "镇江")
                    || StringUtils.contains(address, "无锡") || StringUtils.contains(address, "扬州")
                    || StringUtils.contains(address, "绿能基础") || StringUtils.contains(address, "绿和")) {
                continue;
            }
            String key = type + "," + address;
            AreaConf areaConf = existArea.get(key);
            //position=null,代表无法找到对应地点；line不为空,代表已经做过路径规划
            if (areaConf != null && (areaConf.getPosition() == null || StringUtils.isNotBlank(areaConf.getLine()))) {
                continue;
            }
            boolean isCreate = false;
            if (areaConf == null) {
                areaConf = new AreaConf();
                areaConf.setGisAreaName(address);
                areaConf.setType(type);
                areaConf.setPositionGcj02(null);
                areaConf.setPosition(null);
                areaConf.setCity("常州市");
                areaConf.setDistrict(unitData.getArea());
                isCreate = true;
            }

            //填入地点坐标
            if (StringUtils.isBlank(areaConf.getPosition())) {
                //先判断是否为特殊的地址
                SpecialAddressEnum addressEnum = SpecialAddressEnum.getSpecialAddress(address);
                if (addressEnum != null) {
                    areaConf.setPositionGcj02(addressEnum.getLng().toPlainString()+ "," + addressEnum.getLat().toPlainString());
                } else {
                    //使用高德API查找有无此地点数据，若没有，则定位到所在辖区的中心
                    AreaConf unit = GaodeMapUtils.searchLocation("常州市", address);
                    if (unit == null) {
//                        if (StringUtils.isNotBlank(unitData.getArea())) {
//                            DistrictEnum districtEnum = DistrictEnum.getByDistrictName("常州市", unitData.getArea());
//                            if (districtEnum != null) {
//                                if (StringUtils.isBlank(areaConf.getDistrict()) || DistrictEnum.getByDistrictName("常州市", areaConf.getDistrict()) == null) {
//                                    areaConf.setDistrict(districtEnum.getDistrict());
//                                }
//                                areaConf.setPositionGcj02(districtEnum.getLng().toPlainString() + "," + districtEnum.getLat().toPlainString());
//                            }
//                        }
                        continue;
                    } else {
                        //如果查到了此地点
                        if (StringUtils.isBlank(areaConf.getDistrict()) || DistrictEnum.getByDistrictName("常州市", areaConf.getDistrict()) == null) {
                            areaConf.setDistrict(unit.getDistrict());
                        }
                        areaConf.setPositionGcj02(unit.getPositionGcj02());
                    }
                }
            }

            if (StringUtils.isNotBlank(areaConf.getPositionGcj02())) {
                String[] splits = areaConf.getPositionGcj02().split(",");
                double[] centers = LonlatConver.gcj02_To_Wgs84(Double.parseDouble(splits[0]), Double.parseDouble(splits[1]));
                areaConf.setPosition(centers[0] + "," + centers[1]);
                //做路径规划
                String[] origins = type == 7 ? location_shiyebu.split(",") : splits;
                String[] dests = type == 7 ? splits : location_shiyebu.split(",");
                List<BigDecimal[]> routes = GaodeMapUtils.routePlan(origins[0], origins[1], dests[0], dests[1]);
                if (!routes.isEmpty()) {
                    routes.forEach(ArrayUtil::reverse);
                    areaConf.setLine(JSON.toJSONString(routes));
                }
            }

            if (isCreate) {
                areasToSave.add(areaConf);
            } else {
                areasToUpdate.add(areaConf);
            }

        }
        if (!areasToSave.isEmpty()) {
            areaConfService.insertBatch(areasToSave);
        }
        if (!areasToUpdate.isEmpty()) {
            areaConfService.updateBatch(areasToUpdate);
        }

    }


    /**
     * 导入苏再生地磅运进数据
     */
    public void retrieveFutaiIn() {
        List<WeighbridgeIn> futaiInList = weighbridgeInRepository.findAll(((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> res = new ArrayList<>();
            res.add(criteriaBuilder.isNull(root.get("createTime")));
            return criteriaQuery.where(res.toArray(new Predicate[0])).getRestriction();
        }));
        int count = 0;
        for (WeighbridgeIn weighbridgeIn: futaiInList) {
            if (StringUtils.isBlank(weighbridgeIn.getArea()) && StringUtils.isBlank(weighbridgeIn.getSourceUnit())) {
                continue;
            }
            count ++;
            if (count > 200) {
                break;
            }
            if (weighbridgeIn.getArea().equals("高新区")) {
                weighbridgeIn.setArea("虎丘区");
            }
            //创建运进数据对象，填入地磅数据
            TransportationInHistory inHistory = new TransportationInHistory();
            inHistory.setCreateTime(new Timestamp(System.currentTimeMillis()));
            inHistory.setIsDel(false);
            inHistory.setPositionEnd(location_suzaisheng);
            inHistory.setCarNumber(weighbridgeIn.getCarNo());
            inHistory.setTareWeight(weighbridgeIn.getTareWeight());
            inHistory.setGrossWeight(weighbridgeIn.getGrossWeight());
            inHistory.setDeductionWeight(weighbridgeIn.getDeductWeight());
            inHistory.setNetWeight(weighbridgeIn.getNetWeight());
            inHistory.setCardNumber(weighbridgeIn.getIcCode());
            inHistory.setGoodName(weighbridgeIn.getProductName());
            inHistory.setFeedCompany(weighbridgeIn.getTransportUnit());
            inHistory.setWorkShopName(weighbridgeIn.getProductToWhere());
            if (weighbridgeIn.getTareTimeStr() != null) {
                inHistory.setEnterInTime(new Timestamp(weighbridgeIn.getTareTimeStr().getTime()));
            }
            inHistory.setDisposeCompany("苏州市建筑材料再生资源利用有限公司");

            //先判断是否为特殊的地址
            String address = weighbridgeIn.getSourceUnit();
            SpecialAddressEnum addressEnum = SpecialAddressEnum.getSpecialAddress(address);
            if (addressEnum != null) {
                inHistory.setDeliverCompany(addressEnum.getRealAddress());
                inHistory.setPositionStart(addressEnum.getLng().toPlainString()+ "," + addressEnum.getLat().toPlainString());
                if (StringUtils.isBlank(weighbridgeIn.getArea())) {
                    weighbridgeIn.setArea(addressEnum.getDistrict());
                }
            } else {
                inHistory.setDeliverCompany(weighbridgeIn.getSourceUnit());
                //使用高德API查找有无此地点数据，若没有，则定位到所在辖区的中心
                AreaConf unit = GaodeMapUtils.searchLocation("苏州市", weighbridgeIn.getSourceUnit());
                if (unit == null) {
                    DistrictEnum districtEnum = DistrictEnum.getByDistrictName("苏州市", weighbridgeIn.getArea());
                    if (districtEnum != null) {
                        inHistory.setPositionStart(districtEnum.getLng().toPlainString() + "," + districtEnum.getLat().toPlainString());
                    }
                } else {
                    inHistory.setPositionStart(unit.getPositionGcj02());
                    if (StringUtils.isBlank(weighbridgeIn.getArea())) {
                        weighbridgeIn.setArea(unit.getDistrict());
                    }
                }
            }

            //做路径规划
            if (StringUtils.isNotBlank(inHistory.getPositionStart())) {
                String[] origins = inHistory.getPositionStart().split(",");
                String[] dests = inHistory.getPositionEnd().split(",");
                List<BigDecimal[]> routes = GaodeMapUtils.routePlan(origins[0], origins[1], dests[0], dests[1]);
                if (!routes.isEmpty()) {
                    inHistory.setLinePosition(JSON.toJSONString(routes));
                }
            }
            if ("空车数据".equals(weighbridgeIn.getProductName())) {
                inHistory.setStatus(1);
            }
            inHistory.setArea(weighbridgeIn.getArea());
            weighbridgeIn.setCreateTime(new Date(System.currentTimeMillis()));
            weighbridgeInRepository.save(weighbridgeIn);
            transportationInHistoryRepository.save(inHistory);
        }

    }

    /**
     * 导入苏再生地磅运出数据
     */
    public void retrieveFutaiOut() {
        List<WeighbridgeOut> futaiOutList = weighbridgeOutRepository.findAll(((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> res = new ArrayList<>();
            res.add(criteriaBuilder.isNull(root.get("createTime")));
            res.add(criteriaBuilder.notEqual(root.get("disposeUnitName"), "空车数据"));
            return criteriaQuery.where(res.toArray(new Predicate[0])).getRestriction();
        }));
        int count = 0;
        for (WeighbridgeOut weighbridgeOut: futaiOutList) {
            if (StringUtils.isAllBlank(weighbridgeOut.getArea(), weighbridgeOut.getDisposeUnitName())) {
                continue;
            }
            count++;
            if (count > 200) {
                break;
            }
            if (weighbridgeOut.getArea().equals("高新区")) {
                weighbridgeOut.setArea("虎丘区");
            }
            //创建运出数据对象，填入地磅数据
            TransportationOutHistory outHistory = new TransportationOutHistory();
            outHistory.setCreateTime(new Timestamp(System.currentTimeMillis()));
            outHistory.setPositionStart(location_suzaisheng);
            outHistory.setCarNumber(weighbridgeOut.getCarNo());
            outHistory.setTareWeight(weighbridgeOut.getTareWeight());
            outHistory.setGrossWeight(weighbridgeOut.getGrossWeight());
            outHistory.setDeductionWeight(weighbridgeOut.getDeductWeight());
            outHistory.setNetWeight(weighbridgeOut.getNetWeight());
            outHistory.setCardNumber(weighbridgeOut.getIcCode());
            outHistory.setGoodName(weighbridgeOut.getProductName());
            outHistory.setFeedCompany(weighbridgeOut.getTransportUnit());
            outHistory.setWorkShopName(weighbridgeOut.getProductToWhere());
            if (weighbridgeOut.getTareTimeStr() != null) {
                outHistory.setEnterInTime(new Timestamp(weighbridgeOut.getTareTimeStr().getTime()));
            }
            outHistory.setDeliverCompany("苏州市建筑材料再生资源利用有限公司");

            //先判断是否为特殊的地址
            String address = weighbridgeOut.getDisposeUnitName();
            SpecialAddressEnum addressEnum = SpecialAddressEnum.getSpecialAddress(address);
            if (addressEnum != null) {
                outHistory.setDisposeCompany(addressEnum.getRealAddress());
                outHistory.setPositionEnd(addressEnum.getLng().toPlainString()+ "," + addressEnum.getLat().toPlainString());
                if (StringUtils.isBlank(weighbridgeOut.getArea())) {
                    weighbridgeOut.setArea(addressEnum.getDistrict());
                }
            } else {
                outHistory.setDisposeCompany(address);
                //使用高德API查找有无此地点数据，若没有，则定位到所在行政区域的中心
                AreaConf unit = GaodeMapUtils.searchLocation("苏州市", address);
                if (unit == null) {
                    DistrictEnum districtEnum = DistrictEnum.getByDistrictName("苏州市", weighbridgeOut.getArea());
                    if (districtEnum != null) {
                        outHistory.setPositionEnd(districtEnum.getLng().toPlainString() + "," + districtEnum.getLat().toPlainString());
                    }
                } else {
                    outHistory.setPositionEnd(unit.getPositionGcj02());
                    if (StringUtils.isBlank(weighbridgeOut.getArea())) {
                        weighbridgeOut.setArea(unit.getDistrict());
                    }
                }
            }
            //做路径规划
            if (StringUtils.isNotBlank(outHistory.getPositionEnd())) {
                String[] origins = outHistory.getPositionStart().split(",");
                String[] dests = outHistory.getPositionEnd().split(",");
                List<BigDecimal[]> routes = GaodeMapUtils.routePlan(origins[0], origins[1], dests[0], dests[1]);
                if (!routes.isEmpty()) {
                    outHistory.setLinePosition(JSON.toJSONString(routes));
                }
            }
            outHistory.setArea(weighbridgeOut.getArea());
            weighbridgeOut.setCreateTime(new Date(System.currentTimeMillis()));
            weighbridgeOutRepository.save(weighbridgeOut);
            transportationOutHistoryRepository.save(outHistory);
        }

    }

//    [120.65186795226448,31.298988585880608],[120.65186795226448,31.298988585880608],[120.65182002974073,31.299181596723596],[120.65179307606104,31.29925661609502],[120.65171321301031,31.299481672376185],[120.65159541826256,31.29977177187323],[120.65154649656645,31.299975780185427],[120.65154648252569,31.30014671273203],[120.65156842129589,31.30037258375467],[120.65156842129589,31.30037258375467],[120.65155743778874,31.300431580441654],[120.65146061001407,31.300624680164844],[120.65146061001407,31.300624680164844],[120.65146658959937,31.30073162715943],[120.6515364423894,31.30087144521562],[120.65156837506682,31.3009353620276],[120.65167815148382,31.30105811415837],[120.65167815148382,31.30105811415837],[120.65156837506682,31.3009353620276],[120.6515364423894,31.30087144521562],[120.65146658959937,31.30073162715943],[120.65146061001407,31.300624680164844],[120.65155743778874,31.300431580441654],[120.65156842129589,31.30037258375467],[120.65154648252569,31.30014671273203],[120.65154649656645,31.299975780185427],[120.65159541826256,31.29977177187323],[120.65171321301031,31.299481672376185],[120.65179307606104,31.29925661609502],[120.65182002974073,31.299181596723596],
//
//            [[120.65186795226448,31.298988585880608],[120.65186795226448,31.298988585880608],[120.65182002974073,31.299181596723596],[120.65179307606104,31.29925661609502],[120.65171321301031,31.299481672376185],[120.65159541826256,31.29977177187323],[120.65154649656645,31.299975780185427],[120.65154648252569,31.30014671273203],[120.65156842129589,31.30037258375467],[120.65156842129589,31.30037258375467],[120.65155743778874,31.300431580441654],[120.65146061001407,31.300624680164844],[120.65146061001407,31.300624680164844],[120.65146658959937,31.30073162715943],[120.6515364423894,31.30087144521562],[120.65156837506682,31.3009353620276],[120.65167815148382,31.30105811415837],[120.65167815148382,31.30105811415837],[120.65156837506682,31.3009353620276],[120.6515364423894,31.30087144521562],[120.65146658959937,31.30073162715943],[120.65146061001407,31.300624680164844],[120.65155743778874,31.300431580441654],[120.65156842129589,31.30037258375467],[120.65154648252569,31.30014671273203],[120.65154649656645,31.299975780185427],[120.65159541826256,31.29977177187323],[120.65171321301031,31.299481672376185],[120.65179307606104,31.29925661609502],[120.65182002974073,31.299181596723596],[120.65186795226448,31.298988585880608],[120.65186795226448,31.298988585880608]]
//
//
//
//            [120.64929906977775,31.28479394593795],[120.64947576526897,31.28440179130949],[120.6510337586711,31.284564920649604],[120.65236216474615,31.284681457013477],[120.65254980856776,31.284546169621432],[120.65340611953748,31.284619568918274],[120.65408577086683,31.284683290290605],[120.65408577086683,31.284683290290605],[120.65424644838649,31.284730973870168],[120.65556381358088,31.284851480692236],[120.6564949397577,31.284914717369407],[120.65661769306679,31.284909489889944],[120.65700391142613,31.284945751671067],[120.65754980149723,31.28502469474962],[120.65776336271009,31.28510026226492],[120.658063747839,31.28516866890666],[120.65849686339291,31.285221830828323],[120.66063347929301,31.285426701357597],[120.66112546427176,31.285474746260356],[120.66207849334651,31.285563894269814],[120.6622012391909,31.285573656141796],[120.66347559384498,31.285690174102957],[120.66627575323672,31.285952701170757],[120.66708406314282,31.286020122435247],[120.66801511384784,31.28611029853556],[120.66861984776408,31.286162116756685],[120.66956287244652,31.2862512711208],[120.6704510127675,31.28633053607647],[120.67077233991397,31.286361907648217],[120.67131320860389,31.286403854897838],[120.67134514203681,31.286403793806272],[120.6713770750592,31.286408730673624],[120.6713770750592,31.286408730673624],[120.6714948322595,31.286376518518537],[120.6745674194106,31.2866545440656],[120.6753058826547,31.286739107777382],[120.67564317877583,31.286813438233818],[120.67577190689258,31.286883165991494],[120.67636068668736,31.286936030916255],[120.67681075533584,31.286978164148852],[120.67716402542601,31.287009485537435],[120.68128658725081,31.287350654236995],[120.68193926649104,31.28740842804937],[120.6825869628657,31.287439226727283],[120.68324065366608,31.287454025859383],[120.68408098085061,31.287446500565512],[120.6850710246337,31.287407727247473],[120.68596527086412,31.2873581427374],[120.6868755007139,31.287275554563564],[120.687604095331,31.28718330274223],[120.6882139273318,31.287086269274187],[120.68868004035637,31.28699349089112],[120.6894406011367,31.286842228254645],[120.69108453476237,31.286410575058724],[120.69108453476237,31.286410575058724],[120.69149078675449,31.286280936058944],[120.69213360925296,31.286081928546974],[120.69361692981006,31.285553661428928],[120.70284939751883,31.28224660472644],[120.7034115210312,31.282068864689823],[120.70471851393602,31.28170215610829],[120.70560817145463,31.281507995687825],[120.7064379380068,31.28135691998702],[120.70671153480727,31.28131956421725],[120.70671153480727,31.28131956421725],[120.70770209421428,31.281183293722776],[120.70840908188363,31.28111839016861],[120.70966332057755,31.281052801388704],[120.71039631238654,31.281040882826353],[120.7115647378368,31.281066432560465],[120.71304880180986,31.281118640873867],[120.71314467916679,31.281123526781073],[120.71342931723619,31.281134191307153],[120.71414741705829,31.281154358775748],[120.71414741705829,31.281154358775748],[120.71426527581028,31.281100247453526],[120.71446802794955,31.28107902716435],[120.71469375223789,31.281072776214735],[120.71680425066215,31.281140454978537],[120.71928551530935,31.28121291156434],[120.71948430595185,31.281218716506125],[120.71946229993941,31.281566593676125],[120.71869611576751,31.28154135436961],[120.71680422289464,31.281473317102783],[120.71680422289464,31.281473317102783],[120.71562560038446,31.281436595622825],[120.71461282552332,31.281378740143573],[120.71453791853493,31.281362830884675],[120.71428623558592,31.281272152469487],[120.71342930873561,31.281236149062043],[120.71147385093225,31.281157505351146],[120.71065994561938,31.281137514431098],[120.70996789157523,31.281143378221238],[120.70917499261789,31.28117137607664],[120.70845800395342,31.281215286140654],[120.70779894579489,31.28128012530587],[120.70702207158854,31.281377121473085],[120.70634706320159,31.28147999276639],[120.70552728326126,31.28163705419893],[120.70494915458589,31.281760808153322],[120.70423723925511,31.281933740165798],[120.70325076200835,31.2822250319591],[120.69423781170396,31.28545567457502],[120.69225637551375,31.286161688779494],[120.69149077605219,31.286409883316722],[120.69113243574367,31.28652344713893],[120.69054352688528,31.286690386743032],[120.69000253692779,31.286820264798262],[120.68969211841832,31.286900768430055],[120.68946654241458,31.28695513711367],[120.68859419321628,31.287133583754528],[120.68847142692023,31.287154789922752],[120.68805821455503,31.287236481392135],[120.68651718438848,31.287448121173906],[120.68573470957617,31.287519489594544],[120.68503907470233,31.287563721139595],[120.6842306712241,31.28759716777443],[120.68269972444111,31.28758895917442],[120.68181650210263,31.287547597115054],[120.68114685755248,31.287495853043225],[120.67838948996858,31.287248085892056],[120.677153037845,31.28713245600596],[120.67683769008329,31.287096065192426],[120.67595451850217,31.287016765814794],[120.67572898583258,31.287001199025067],[120.6755423724808,31.286991556400892],[120.67534877436415,31.286974930088014],[120.6722652024565,31.28667592301977],[120.67134512701875,31.286585719418298],[120.67105573250055,31.286560283792],[120.66956285867316,31.286418202835534],[120.66835239382978,31.286307570472218],[120.66542950507046,31.286072275367797],[120.66385578905586,31.285892363886866],[120.66228205815243,31.28574543153632],[120.65881320308479,31.28542015241424],[120.65738311568572,31.285304892831768],[120.65730826751928,31.285299035749993],[120.65553085474575,31.28515241847014],[120.65507576779052,31.28510528381506],[120.65447696560088,31.285036422088425],[120.65387716051558,31.28496755847309],[120.65387716051558,31.28496755847309],[120.65207771126103,31.284793929943387],[120.65095390331015,31.28468401619891],[120.64951368102534,31.28454666391539],
//
//
//            [120.57455861264934,31.298377185076664],[120.57455861264934,31.298377185076664],[120.57549877556137,31.298479919221496],[120.5757080271031,31.298513073163484],[120.57624566472116,31.298572469918028],[120.5766371187927,31.298620748652326],[120.57671821174162,31.29863180511742],[120.57750709840796,31.29872834338871],[120.57836602501992,31.29884189433125],[120.57863030194738,31.2988790562973],[120.57897365783394,31.29890627037709],[120.57916184961181,31.298928382615415],[120.57980549159532,31.298997756918254],[120.58026193290998,31.29905200905956],[120.58122282528478,31.299165509496444],[120.58176030216191,31.29923576861318],[120.58198549760552,31.29926187463177],[120.58206656716135,31.29927291159123],[120.58230777247992,31.299300022071797],[120.58230777247992,31.299300022071797],[120.58227573198927,31.29946094250868],[120.58205554490453,31.299428844342838],[120.58176028953297,31.29939070734623],[120.58162617187638,31.299374643322654],[120.58160414434936,31.299471593365897],[120.58158812093552,31.299583540651568],[120.58157209612263,31.29971248122654],[120.58151299079019,31.300356195793487],[120.58147592609289,31.30074202397265],[120.58143787223466,31.300982908757312],[120.58140083313559,31.301052861335137],[120.58135178529177,31.301095817995904],[120.58126070089035,31.3011167603759],[120.5811556052479,31.301112704531693],[120.5811556052479,31.301112704531693],[120.58112657871871,31.30111168897918],[120.58098745404345,31.3010686289372],[120.58092740491047,31.300988626924052],[120.58091139533381,31.300923643544966],[120.58096546511486,31.30068276860746],[120.58103561421706,31.299648215704494],[120.58106265012685,31.299513283985664],[120.58108367990347,31.299385346173082],[120.58108367990347,31.299385346173082],[120.58071834505054,31.29932616484002],[120.580412062645,31.299229026981706],[120.57975242805944,31.299132671124276],[120.57913981613765,31.29906231553373],[120.57897364642375,31.299046214989573],[120.57861927984418,31.29900799796128],[120.57832897497003,31.298970818283156],[120.57771131049421,31.298900419945493],[120.57695947443888,31.298808914259634],[120.5762026020296,31.29871737933818],[120.57568098256931,31.298657994272737],[120.57452656137986,31.2985061068759],[120.57452656137986,31.2985061068759],[120.57448850060405,31.298657014842036],[120.57440837345226,31.298961826055823],[120.57439234724656,31.299031784715993],[120.57427916792318,31.299450522353997],[120.57415597024266,31.29992722808124],[120.57397868650044,31.300586814257034],[120.57395164385885,31.300677754860047],[120.5735860457924,31.30212486410464],[120.57356500964043,31.30222680541317],[120.57341976779756,31.302827440359223],[120.57323746030636,31.303609970182375],[120.57319939779602,31.303749881080083],[120.57297402199595,31.304628333110756],[120.57283378719505,31.30516999334971],[120.57265148181699,31.305856557658583],[120.57243611719257,31.306687034192844],[120.57221073823023,31.30749150995552],

    public void  setCj02(){
        List<Transportation> all = transportationRepository.findAll();
        for(Transportation transportation:all){
            log.info("修改前的值:{}",transportation);
            String area = transportation.getArea();
            String[] split = area.split(",");
            double[] doubles = LonlatConver.wgs84_To_Gcj02(Double.parseDouble(split[0].replaceAll(" ", "")), Double.parseDouble(split[1].replaceAll(" ", "")));
            transportation.setArea(doubles[0]+","+doubles[1]);
            String luguo = transportation.getLuguo();
            StringBuilder ele = new StringBuilder();
            String[] luguodian = luguo.split(";");
            for(String dian:luguodian){
                    if(StrUtil.isNotEmpty(dian)){
                        String[] strArr = dian.split(",");
                        double[] strPoint = LonlatConver.wgs84_To_Gcj02(Double.parseDouble(strArr[0].replaceAll(" ", "")), Double.parseDouble(strArr[1].replaceAll(" ", "")));
                        ele.append(strPoint[0]+","+strPoint[1]+";");
                    }
            }
            transportation.setLuguo(ele.toString());
            log.info("修改后的值:{}",transportation);
            transportationRepository.save(transportation);
        }
    }

    public void makeData(){
            //先换取坐标
        AreaConf areaConf = areaConfRepository.findById(1L).orElseGet(AreaConf::new);
        List<Transportation> transportationOutHistoryList = transportationRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> res = new ArrayList<>();
            res.add(criteriaBuilder.equal(root.get("type").as(Boolean.class), false));
            res.add(criteriaBuilder. isNotNull(root.get("area").as(String.class)));
            res.add(criteriaBuilder. isNull(root.get("line").as(String.class)));
            return criteriaQuery.where(res.toArray(new Predicate[res.size()])).getRestriction();
        });
        RestTemplate restTemplate = new RestTemplate();
        int count = 0;
        for(Transportation transportationInHistory:transportationOutHistoryList){
            //换取参数
            String[] gcjo2 = transportationInHistory.getLuguo().split(",");
//            double[] doubles = LonlatConver.gcj02_To_Wgs84(new BigDecimal(gcjo2[0]).doubleValue(), new BigDecimal(gcjo2[1]).doubleValue());
//            String wgs84 = doubles[0]+","+doubles[1];
            ResponseEntity<String> forEntity = restTemplate.getForEntity("https://restapi.amap.com/v5/direction/driving?" +
                            "key=a55d9d3ac4c5c777f76415b080f76000" +
                            "&origin=" + transportationInHistory.getArea()  +
                            "&destination="+ gcjo2[0]+ "," + gcjo2[1] +
                            "&strategy=3,43"+//速度优先
//                            (StrUtil.isNotEmpty(transportationInHistory.getLuguo())?("&waypoints="+transportationInHistory.getLuguo()):"")+
                            "&show_fields=polyline"
                    , String.class);
            if(new Integer(200).equals(forEntity.getStatusCodeValue())){
                String body = forEntity.getBody();
                JSONObject res = JSONObject.parseObject(body, JSONObject.class);
                if("1".equals(res.getString("status"))){
                    //表示查询结果正常了，接下来做处理
//                    if("1".equals(res.getString("count"))){
                    //表述这有确切的地点
                    String route = res.getString("route");
                    JSONObject routeArray = JSONObject.parseObject(route, JSONObject.class);
                    List<double[]> linePoint = new ArrayList<>();
                    String paths = routeArray.getString("paths");
                    List<JSONObject> pathArray = JSONArray.parseArray(paths,JSONObject.class);
                    JSONObject jsonPath = pathArray.get(0);
                    String steps = jsonPath.getString("steps");
                    List<JSONObject> stepsArray = JSONArray.parseArray(steps,JSONObject.class);
                    for(JSONObject ele:stepsArray){
                        String polylineStr = ele.getString("polyline");
                        String[] split = polylineStr.split(";");
                        for(String str :split){
                            String[] position = str.split(",");
                            double[] par = LonlatConver.gcj02_To_Wgs84(new BigDecimal(position[0]).doubleValue(),new BigDecimal(position[1]).doubleValue() );
                            linePoint.add(par);
                        }
                    }
                    log.info("当前路径坐标{}",linePoint);
                    transportationInHistory.setLine(JSONArray.toJSONString(linePoint));
                    log.info("执行了{}",count++);
                    log.info("执行修改");
                    transportationRepository.save(transportationInHistory);
                    log.info("修改成功");
//                    }else{
//                        log.info("执行失败");
//                        return;
//                    }
                }else{
                    log.info("执行失败");
                    return;
                }
            }else{
                log.info("执行失败");
                return;
            }
        }

    }


    public void sysTransportationDataOut(){
        List<Map<String,String>> mapList = transportationOutHistoryRepository.sysTransportationData();
        for(Map<String,String> ele :mapList){
            Transportation  transportation = new Transportation();
            transportation.setSumWeight(MapUtil.get(ele,"weight",BigDecimal.class));
            transportation.setType(true);
            List<Double[]> line = JSONArray.parseArray(ele.get("line"), Double[].class);
            //转换坐标系
            List<double[]> wgs84Point = new ArrayList<>();
            for(Double[] point:line){
                double[] par = LonlatConver.gcj02_To_Wgs84(point[0].doubleValue(),point[1].doubleValue() );
                wgs84Point.add(par);
            }
            String wgs84Line = JSONArray.toJSONString(wgs84Point);
            transportation.setLine(wgs84Line);
            String enterTime = ele.get("enterTime");
            String weights = ele.get("weights");
            String ids = ele.get("ids");
            String goodName = ele.get("goodName");
            String[] enterTimeArrray = enterTime.split(",");
            String[] weightsArray = weights.split(",");
            String[] idsArray = ids.split(",");
            String[] goodNameArray = goodName.split(",");
            JSONArray content = new JSONArray();
            for(int i = 0; i< enterTimeArrray.length;i++){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("enterTime",DateUtil.parse(enterTimeArrray[i], DatePattern.NORM_DATETIME_PATTERN));
                jsonObject.put("id",Long.parseLong(idsArray[i]));
                jsonObject.put("weight",new BigDecimal(weightsArray[i]));
                jsonObject.put("type",getTypeOutUtil(goodNameArray[i]));
                jsonObject.put("status",false);
                content.add(jsonObject);
            }
            transportation.setContent(JSONArray.toJSONString(content));
            transportationRepository.save(transportation);
        }
    }

    public void sysTransportationData(){
        List<Map<String,String>> mapList = transportationInHistoryRepository.sysTransportationData();
        for(Map<String,String> ele :mapList){
            Transportation  transportation = new Transportation();
            transportation.setSumWeight(MapUtil.get(ele,"weight",BigDecimal.class));
            List<Double[]> line = JSONArray.parseArray(ele.get("line"), Double[].class);
            //转换坐标系
            List<double[]> wgs84Point = new ArrayList<>();
            for(Double[] point:line){
                double[] par = LonlatConver.gcj02_To_Wgs84(point[0].doubleValue(),point[1].doubleValue() );
                wgs84Point.add(par);
            }
            String wgs84Line = JSONArray.toJSONString(wgs84Point);
            transportation.setLine(wgs84Line);
            String enterTime = ele.get("enterTime");
            String weights = ele.get("weights");
            String ids = ele.get("ids");
            String goodName = ele.get("goodName");
            String[] enterTimeArrray = enterTime.split(",");
            String[] weightsArray = weights.split(",");
            String[] idsArray = ids.split(",");
            String[] goodNameArray = goodName.split(",");
            JSONArray content = new JSONArray();
            for(int i = 0; i< enterTimeArrray.length;i++){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("enterTime",DateUtil.parse(enterTimeArrray[i], DatePattern.NORM_DATETIME_PATTERN));
                jsonObject.put("id",Long.parseLong(idsArray[i]));
                jsonObject.put("weight",new BigDecimal(weightsArray[i]));
                jsonObject.put("type",getTypeUtil(goodNameArray[i]));
                jsonObject.put("status",false);
                content.add(jsonObject);
            }
            transportation.setContent(JSONArray.toJSONString(content));
            transportationRepository.save(transportation);
        }
    }
    private Integer getTypeUtil(String typeName){
            if(typeName.contains("装修")){
                return 1;
            }else if(typeName.contains("拆迁")){
                return 2;
            }else if(typeName.contains("拆建")){
                return 3;
            }else{
                return 4;
            }
    }

    private Integer getTypeOutUtil(String typeName){
        if(typeName.contains("建筑")){
            return 5;
        }else if(typeName.contains("水泥块")){
            return 6;
        }else if(typeName.contains("机制砂")){
            return 7;
        }else{
            return 8;
        }
    }


    public void setAreaConf(){
//            String[] areas = new String[]{"苏州市建筑材料再生资源利用有限公司","强胜路与澄浦路交叉口"};
//            log.info("开始获取高德的数据为{}",areas);
//            RestTemplate restTemplate = new RestTemplate();
//            for(String area:areas){
//                ResponseEntity<String> forEntity = restTemplate.getForEntity("https://restapi.amap.com/v3/geocode/geo?" +
//                                "key=a55d9d3ac4c5c777f76415b080f76000" +
//                                "&address=" +area
//                        , String.class);
//                if(new Integer(200).equals(forEntity.getStatusCodeValue())){
//                    String body = forEntity.getBody();
//                    JSONObject res = JSONObject.parseObject(body, JSONObject.class);
//                    if("1".equals(res.getString("status"))){
//                        //表示查询结果正常了，接下来做处理
//                        if("1".equals(res.getString("count"))){
//                            //表述这有确切的地点
//                            String geocodes = res.getString("geocodes");
//                            List<JSONObject> geoJsonArray = JSONArray.parseArray(geocodes, JSONObject.class);
//                            JSONObject geoJson = geoJsonArray.get(0);
//                            String location = geoJson.getString("location");
//                            AreaConf areaConf = new AreaConf();
//                            areaConf.setGisAreaName(area);
//                            areaConf.setPositionGcj02(location);
//                            String position = LonlatConver.gcj02_To_Wgs84(location);
//                            areaConf.setPosition(position);
//                            areaConfRepository.save(areaConf);
//                            log.info("执行成功");
//                        }
//                    }
//                }
//            }

        List<AreaConf> areaConfs = areaConfRepository.findAll();
        for(AreaConf areaConf:areaConfs){
            String positionGcj02 = areaConf.getPositionGcj02();
            String[] positions = positionGcj02.split(",");
            double[] doubles1 = LonlatConver.gcj02_To_Wgs84(Double.parseDouble(positions[0]), Double.parseDouble(positions[1]));
            areaConf.setPosition(doubles1[0]+","+doubles1[1]);
            areaConfRepository.save(areaConf);
//            double[] doubles = LonlatConver.gcj02_To_Wgs84(ele[0].doubleValue(), ele[1].doubleValue());
        }



    }


    public void setTransportationOutHistoryRepository(){

            log.info("setTransportationOutHistoryRepository 开始执行");
            AreaConf areaConf = areaConfRepository.findById(1L).orElseGet(AreaConf::new);
        List<TransportationOutHistory> transportationOutHistoryList = transportationOutHistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> res = new ArrayList<>();
            res.add(criteriaBuilder.equal(root.get("isDel").as(Boolean.class), false));
            res.add(criteriaBuilder.notEqual(root.get("area").as(String.class), ""));
            res.add(criteriaBuilder.isNotNull(root.get("enterInTime")));

            return criteriaQuery.where(res.toArray(new Predicate[res.size()])).getRestriction();
        });
        log.info("查询到数据{}",transportationOutHistoryList.size());
            RestTemplate restTemplate = new RestTemplate();
            int count = 0;
            for(TransportationOutHistory transportationOutHistory:transportationOutHistoryList){
                //换取参数
                if(StrUtil.hasEmpty(transportationOutHistory.getArea())){
                    continue;
                }
                ResponseEntity<String> forEntity = restTemplate.getForEntity("https://restapi.amap.com/v3/geocode/geo?" +
                                "key=a55d9d3ac4c5c777f76415b080f76000" +
                                "&address=苏州市" + transportationOutHistory.getArea()
                        , String.class);
                if(new Integer(200).equals(forEntity.getStatusCodeValue())){
                    String body = forEntity.getBody();
                    JSONObject res = JSONObject.parseObject(body, JSONObject.class);
                    if("1".equals(res.getString("status"))){
                        //表示查询结果正常了，接下来做处理
//                    if("1".equals(res.getString("count"))){
                        //表述这有确切的地点
                        String geocodes = res.getString("geocodes");
                        List<JSONObject> geoJsonArray = JSONArray.parseArray(geocodes, JSONObject.class);
                        JSONObject geoJson = geoJsonArray.get(0);
                        String location = geoJson.getString("location");
                        transportationOutHistory.setPositionStart(areaConf.getPositionGcj02());
                        transportationOutHistory.setPositionEnd(location);
                        log.info("执行修改");
                        TransportationOutHistory save = transportationOutHistoryRepository.save(transportationOutHistory);
                        log.info("修改成功，{}",save);
                        log.info("执行了{}",count++);
//                    }else{
//                        log.info("失败");
//                        return;
//                    }
                    }else{
                        log.info("失败");
                        return;
                    }
                }else{
                    log.info("失败");
                    return;
                }
            }


    }
    public void setTransportationInHistoryLine(){
        log.info("setTransportationInHistoryLine 开始执行");
        List<TransportationInHistory> transportationInHistories = transportationInHistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) ->{
            List<Predicate> queryParams= new ArrayList<>();
            queryParams.add(criteriaBuilder.equal(root.get("isDel").as(Boolean.class), false));
            queryParams.add(criteriaBuilder.isNotNull(root.get("positionStart")));
            return criteriaQuery.where(queryParams.toArray(new Predicate[queryParams.size()])).getRestriction();
        });
        log.info("查询到数据{}",transportationInHistories.size());
        RestTemplate restTemplate = new RestTemplate();
        int count = 0;
        for(TransportationInHistory transportationInHistory:transportationInHistories){
            //换取参数
            ResponseEntity<String> forEntity = restTemplate.getForEntity("https://restapi.amap.com/v5/direction/driving?" +
                            "key=a55d9d3ac4c5c777f76415b080f76000" +
                            "&origin=" + transportationInHistory.getPositionStart()+
                            "&destination="+transportationInHistory.getPositionEnd()+
                            "&strategy=0,2,3,35"+//速度优先

                            "&show_fields=polyline"
                    , String.class);
            if(new Integer(200).equals(forEntity.getStatusCodeValue())){
                String body = forEntity.getBody();
                JSONObject res = JSONObject.parseObject(body, JSONObject.class);
                if("1".equals(res.getString("status"))){
                    //表示查询结果正常了，接下来做处理
//                    if("1".equals(res.getString("count"))){
                    //表述这有确切的地点
                    String route = res.getString("route");
                    JSONObject routeArray = JSONObject.parseObject(route, JSONObject.class);
                    List<BigDecimal[]> linePoint = new ArrayList<>();
                    String paths = routeArray.getString("paths");
                    List<JSONObject> pathArray = JSONArray.parseArray(paths,JSONObject.class);
                    JSONObject jsonPath = pathArray.get(0);
                    String steps = jsonPath.getString("steps");
                    List<JSONObject> stepsArray = JSONArray.parseArray(steps,JSONObject.class);
                    for(JSONObject ele:stepsArray){
                        String polylineStr = ele.getString("polyline");
                        String[] split = polylineStr.split(";");
                        for(String str :split){
                            String[] position = str.split(",");
                            linePoint.add(new BigDecimal[]{new BigDecimal(position[0]),new BigDecimal(position[1])});
                        }
                    }
                    log.info("当前路径坐标{}",linePoint);
                    transportationInHistory.setLinePosition(JSONArray.toJSONString(linePoint));
                    log.info("执行了{}",count++);
                    log.info("执行修改");
                    transportationInHistoryRepository.save(transportationInHistory);
                    log.info("修改成功");
//                    }else{
//                        log.info("执行失败");
//                        return;
//                    }
                }else{
                    log.info("执行失败");
                    return;
                }
            }else{
                log.info("执行失败");
                return;
            }
        }

    }




    /**
     * 根据地名获取地址信息坐标
     */
    public  void setTransportationInHistory(){
        log.info("setTransportationInHistory 开始执行");
        AreaConf areaConf = areaConfRepository.findById(1L).orElseGet(AreaConf::new);
        List<TransportationInHistory> transportationInHistories = transportationInHistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) ->{
            Predicate like = criteriaBuilder.equal(root.get("isDel").as(Boolean.class), false);
            return criteriaQuery.where(like).getRestriction();
        });
        log.info("查询到数据{}",transportationInHistories.size());
        RestTemplate restTemplate = new RestTemplate();
        int count = 0;
        for(TransportationInHistory transportationInHistory:transportationInHistories){
            ConcurrentHashMap<String,String> params = new ConcurrentHashMap<>();
            //换取参数
            if(StrUtil.hasEmpty(transportationInHistory.getArea())){
                continue;
            }
            ResponseEntity<String> forEntity = restTemplate.getForEntity("https://restapi.amap.com/v3/geocode/geo?" +
                            "key=a55d9d3ac4c5c777f76415b080f76000" +
                            "&address=苏州市" + transportationInHistory.getArea()+transportationInHistory.getDeliverCompany()
                    , String.class);
            if(new Integer(200).equals(forEntity.getStatusCodeValue())){
                String body = forEntity.getBody();
                JSONObject res = JSONObject.parseObject(body, JSONObject.class);
                if("1".equals(res.getString("status"))){
                    //表示查询结果正常了，接下来做处理
//                    if("1".equals(res.getString("count"))){
                        //表述这有确切的地点
                        String geocodes = res.getString("geocodes");
                        List<JSONObject> geoJsonArray = JSONArray.parseArray(geocodes, JSONObject.class);
                        JSONObject geoJson = geoJsonArray.get(0);
                        String location = geoJson.getString("location");
                        transportationInHistory.setPositionStart(location);
                        transportationInHistory.setPositionEnd(areaConf.getPositionGcj02());
                        log.info("执行修改");
                        TransportationInHistory save = transportationInHistoryRepository.save(transportationInHistory);
                        log.info("修改成功，{}",save);
                        log.info("执行了{}",count++);
//                    }else{
//                        log.info("失败");
//                        return;
//                    }
                }else{
                    log.info("失败");
                    return;
                }
            }else{
                log.info("失败");
                return;
            }
        }


    }

    public void setTransportationOutHistoryLine(){
        log.info("setTransportationInHistoryLine 开始执行");
        List<TransportationOutHistory> transportationInHistories = transportationOutHistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) ->{
            List<Predicate> queryParams= new ArrayList<>();
            queryParams.add(criteriaBuilder.equal(root.get("isDel").as(Boolean.class), false));
            queryParams.add(criteriaBuilder.isNotNull(root.get("positionStart")));
            return criteriaQuery.where(queryParams.toArray(new Predicate[queryParams.size()])).getRestriction();
        });
        log.info("查询到数据{}",transportationInHistories.size());
        RestTemplate restTemplate = new RestTemplate();
        int count = 0;
        for(TransportationOutHistory transportationInHistory:transportationInHistories){
            //换取参数
            ResponseEntity<String> forEntity = restTemplate.getForEntity("https://restapi.amap.com/v5/direction/driving?" +
                            "key=a55d9d3ac4c5c777f76415b080f76000" +
                            "&origin=" + transportationInHistory.getPositionStart()+
                            "&destination="+transportationInHistory.getPositionEnd()+
                            "&strategy=0,2,3,35"+//速度优先
                            "&show_fields=polyline"
                    , String.class);
            if(new Integer(200).equals(forEntity.getStatusCodeValue())){
                String body = forEntity.getBody();
                JSONObject res = JSONObject.parseObject(body, JSONObject.class);
                if("1".equals(res.getString("status"))){
                    //表示查询结果正常了，接下来做处理
//                    if("1".equals(res.getString("count"))){
                        //表述这有确切的地点
                        String route = res.getString("route");
                        JSONObject routeArray = JSONObject.parseObject(route, JSONObject.class);
                        List<BigDecimal[]> linePoint = new ArrayList<>();
                        String paths = routeArray.getString("paths");
                        List<JSONObject> pathArray = JSONArray.parseArray(paths,JSONObject.class);
                        JSONObject jsonPath = pathArray.get(0);
                        String steps = jsonPath.getString("steps");
                        List<JSONObject> stepsArray = JSONArray.parseArray(steps,JSONObject.class);
                        for(JSONObject ele:stepsArray){
                            String polylineStr = ele.getString("polyline");
                            String[] split = polylineStr.split(";");
                            for(String str :split){
                                String[] position = str.split(",");
                                linePoint.add(new BigDecimal[]{new BigDecimal(position[0]),new BigDecimal(position[1])});
                            }
                        }
                        log.info("当前路径坐标{}",linePoint);
                        transportationInHistory.setLinePosition(JSONArray.toJSONString(linePoint));
                        log.info("执行了{}",count++);
                        log.info("执行修改");
                    transportationOutHistoryRepository.save(transportationInHistory);
                        log.info("修改成功");
//                    }else{
//                        log.info("执行失败");
//                        return;
//                    }
                }else{
                    log.info("执行失败");
                    return;
                }
            }else{
                log.info("执行失败");
                return;
            }
        }

    }



    /**
     * 根据起点和终点选择道路
     */
    public void getLinePosition(){
        //获取数据库中已经做过  《根据地名获取地址信息坐标》 处理的信息数据
        log.info("getLinePosition 开始执行");
        List<FeedHistory> feedHistoryAll = feedHistoryRepository.findAllByPositionStartLatIsNotNullAndLinePositionIsNull();
        log.info("查询到数据{}",feedHistoryAll.size());
        RestTemplate restTemplate = new RestTemplate();
        int count = 0;
        for(FeedHistory feedHistory:feedHistoryAll){
            //换取参数
            ResponseEntity<String> forEntity = restTemplate.getForEntity("https://restapi.amap.com/v5/direction/driving?" +
                            "key=a55d9d3ac4c5c777f76415b080f76000" +
                            "&origin=" + feedHistory.getOrigin()+
                            "&destination="+feedHistory.getDestination()+
                            "&strategy=0"+//速度优先
                            "&show_fields=polyline"
                    , String.class);
            if(new Integer(200).equals(forEntity.getStatusCodeValue())){
                String body = forEntity.getBody();
                JSONObject res = JSONObject.parseObject(body, JSONObject.class);
                if("1".equals(res.getString("status"))){
                    //表示查询结果正常了，接下来做处理
                    if("1".equals(res.getString("count"))){
                        //表述这有确切的地点
                        String route = res.getString("route");
                        JSONObject routeArray = JSONObject.parseObject(route, JSONObject.class);
                        List<BigDecimal[]> linePoint = new ArrayList<>();
                        String paths = routeArray.getString("paths");
                        List<JSONObject> pathArray = JSONArray.parseArray(paths,JSONObject.class);
                        JSONObject jsonPath = pathArray.get(0);
                        String steps = jsonPath.getString("steps");
                        List<JSONObject> stepsArray = JSONArray.parseArray(steps,JSONObject.class);
                        for(JSONObject ele:stepsArray){
                                String polylineStr = ele.getString("polyline");
                                String[] split = polylineStr.split(";");
                                for(String str :split){
                                    String[] position = str.split(",");
                                    linePoint.add(new BigDecimal[]{new BigDecimal(position[0]),new BigDecimal(position[1])});
                                }
                            }
                            log.info("当前路径坐标{}",linePoint);
                        feedHistory.setLinePosition(JSONArray.toJSONString(linePoint));
                        log.info("执行了{}",count++);
                    }
                }
            }
        }
        log.info("执行修改");
        feedHistoryRepository.saveAll(feedHistoryAll);
        log.info("修改成功");
    }


    /**
     * 同步运输历史数据为线条数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void synchronizeTimeLine(){
        List<FeedHistory> feedHistoryList = feedHistoryRepository.getByDateFor("2022-07");
        for(FeedHistory feedHistory:feedHistoryList){
            TimeLine timeLine = new TimeLine();
            timeLine.setId(feedHistory.getId());
            timeLine.setEnterInTime(feedHistory.getEnterInTime());
            timeLine.setLinePosition(feedHistory.getLinePosition());
            log.info("保存数据{},{}",timeLineRepository.save(timeLine),timeLine);
        }

    }


}
